package org.bookie.web.pages.admin;

import java.util.Date;

import org.apache.tapestry.IExternalPage;
import org.apache.tapestry.IRequestCycle;
import org.apache.tapestry.annotations.InjectObject;
import org.apache.tapestry.annotations.Persist;
import org.apache.tapestry.engine.ILink;
import org.apache.tapestry.event.PageBeginRenderListener;
import org.apache.tapestry.event.PageEvent;
import org.bookie.framework.CommonBasePage;
import org.bookie.model.Event;
import org.bookie.model.services.EventDAO;

public abstract class EditEventExt extends CommonBasePage implements
		IExternalPage, PageBeginRenderListener {

	public void activateExternalPage(Object[] parameters, IRequestCycle cycle) {
		if (parameters.length != 1) {
			throw new RuntimeException("Need one Long parameter event ID");
		}
		setEventId((Long) parameters[0]);
	}

	public ILink doSave() {
		long date = getEvent().getEndDate().getTime();
		long time = getTime().getTime();
		getEvent().setEndDate(new Date(date + time));
		return getPageService().getLink(false, getPageName());
	}

	/**
	 * Returns currently edited {@link Event}
	 * 
	 * @return
	 */
	public Event getEvent() {
		return getEventDAO().findById(getEventId());
	}

	/**
	 * Injected {@link EventDAO} service.
	 * 
	 * @return instance of EventDAO
	 */
	@InjectObject("service:bookie.model.EventDAO")
	public abstract EventDAO getEventDAO();

	@Persist
	public abstract Long getEventId();

	public abstract Date getTime();

	/**
	 * This method takes care that time parameter is filled with value
	 */
	public void pageBeginRender(PageEvent event) {
		if (getEventId() != null) {
			setTime(getEvent().getEndDate());
		}
	}

	public abstract void setEventId(Long value);

	public abstract void setTime(Date date);
}
